package br.com.serinus.webapp;

import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class WebConnector {

    private final static long DEFAULT_TIMEOUT = 5000;
    public WebDriver          driver          = new FirefoxDriver();

    public void close() {
        if (this.driver != null) {
            this.driver.close();
        }
    }

    public void clickLinkAndWait(String selector) {
        WebElement element = this.driver.findElement(By.linkText(selector));
        element.click();
        this.driver.manage().timeouts().implicitlyWait(WebConnector.DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS);
    }

    public void clickAndWait(String selector) {
        WebElement element = this.driver.findElement(By.id(selector));
        element.click();
        this.driver.manage().timeouts().implicitlyWait(WebConnector.DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS);
    }

    public void clickElementAndWait(String selector) {
        WebElement element = this.driver.findElement(By.xpath(selector));
        element.click();
        this.driver.manage().timeouts().implicitlyWait(WebConnector.DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS);
    }

    public void openAndWait(String location) {
        this.driver.get(location);
    }

    public void sendKeys(String name, String value) {
        this.driver.findElement(By.name(name)).sendKeys(value);
    }

    public boolean isTextPresent(String text) {
        WebElement content = this.driver.findElement(By.tagName("body"));
        Pattern p = Pattern.compile(text);
        Matcher m = p.matcher(content.getText());
        return m.find();
    }

}
